package com.ruoyi.project.mahjong.controller.api;


import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.domain.Result;
import com.ruoyi.project.mahjong.domain.*;
import com.ruoyi.project.mahjong.domain.dto.ProductExchangeDto;
import com.ruoyi.project.mahjong.domain.dto.RechargeDto;
import com.ruoyi.project.mahjong.domain.vo.MemberCountVo;
import com.ruoyi.project.mahjong.domain.vo.MemberIntegralVo;
import com.ruoyi.project.mahjong.domain.vo.RechargeCompleteVo;
import com.ruoyi.project.mahjong.mapper.TIntegralMapper;
import com.ruoyi.project.mahjong.mapper.TRechargeMoneyMapper;
import com.ruoyi.project.mahjong.mapper.TShopsMapper;
import com.ruoyi.project.mahjong.service.*;
import com.ruoyi.project.system.domain.SysUser;
import io.swagger.annotations.*;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 会员管理相关操作
 */
@RestController
@RequestMapping("/mahjong/members")
@Api(tags = "会员管理相关操作api")
public class MemberApiController {

    @Autowired
    private ITIntegralService itIntegralService;

    @Autowired
    private TShopsMapper tShopsMapper;
    @Autowired
    private TIntegralMapper tIntegralMapper;
    @Autowired
    private TRechargeMoneyMapper tRechargeMoneyMapper;
    @Autowired
    private ICommodityService commodityService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ITMemberService itMemberService;
    @Autowired
    private ITMemberLogService tMemberLogService;


    /**
     * 会员充值
     *
     * @return
     */
    @GetMapping("/memberRecharge")
    @ApiOperation(value = "会员充值操作", httpMethod = "GET")
    @RepeatSubmit
    public AjaxResult memberRecharge(RechargeDto dto) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        RechargeCompleteVo vo = itMemberService.updateTMemberMoney(dto, shopId, user.getUserId());
        if (ObjectUtil.isNull(vo)) {
            return AjaxResult.error("充值失败请重试");
        }
        return AjaxResult.success(vo);
    }

    /**
     * 会员积分消费详情
     *
     * @return
     */
    @GetMapping("/memberIntegral")
    @ApiOperation(value = "会员积分消费详情", httpMethod = "GET")
    @RepeatSubmit
    public AjaxResult memberIntegral(@ApiParam("开始日期") @RequestParam(value = "startTime", required = false) String startTime,
                                     @ApiParam("结束日期") @RequestParam(value = "endTime", required = false) String endTime,
                                     @ApiParam("会员id") @RequestParam(value = "id", required = false) Long id) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        List<MemberIntegralVo> vo = itMemberService.selectMemberIntegral(shopId, id, startTime, endTime);
        if (ObjectUtil.isNull(vo)) {
            return AjaxResult.error("暂无积分信息");
        }
        return AjaxResult.success(vo);
    }

    /**
     * 设置会员充值和消费赠送积分
     *
     * @param tIntegral
     * @return
     */
    @PostMapping("/setGive")
    @ApiOperation(value = "设置会员充值和消费赠送积分", httpMethod = "POST")
    @RepeatSubmit
    public Result setGive(@RequestBody @Validated TIntegral tIntegral) {
        String status = null;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        tIntegral.setShopId(shopId);
        if (tIntegral.getId() != null) {
            tIntegral.setUpdateBy(user.getUserId().toString());
            int i = itIntegralService.updateTIntegral(tIntegral);
            status = i == 0 ? "修改失败" : "修改成功";
            return Result.success(status);
        }
        int i = itIntegralService.insertTIntegral(tIntegral);
        status = i == 0 ? "添加失败" : "添加成功";
        return Result.success(status);
    }

    /**
     * 查询会员充值和消费赠送积分
     *
     * @return
     */
    @GetMapping("/getMemberRecharge")
    @ApiOperation(value = "查询会员充值和消费赠送积分比例", httpMethod = "GET")
    public Result<TIntegral> getMemberRecharge() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        TIntegral tIntegral = new TIntegral();
        tIntegral.setShopId(shopId);
        List<TIntegral> tIntegrals = tIntegralMapper.selectTIntegralList(tIntegral);
        if (ObjectUtil.isEmpty(tIntegrals)) {
            return Result.success("暂无设置赠送数据");
        }
        return Result.success(tIntegrals);
    }


    /**
     * 设置和修改会员充值赠送 点数=金额
     *
     * @return
     */
    @PostMapping("/setRecharge")
    @ApiOperation(value = "设置会员充值赠送点数(金额),带id是新增 ，不带id是修改", httpMethod = "POST")
    @RepeatSubmit
    public Result setRecharge(@RequestBody @Validated TRechargeMoney tRechargeMoney) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());

        String status = null;
        if (tRechargeMoney.getId() != null) {
            tRechargeMoney.setBak2(shopId.toString());
            tRechargeMoney.setBak2(shopId.toString());
            tRechargeMoney.setUpdateBy(user.getUserId().toString());
            tRechargeMoney.setUpdateTime(new Date());
            int i = tRechargeMoneyMapper.updateTRechargeMoney(tRechargeMoney);
            status = i == 0 ? "修改失败" : "修改成功";
            return Result.success(status);
        }
        tRechargeMoney.setCreateTime(DateUtils.getNowDate());
        tRechargeMoney.setBak1("0");
        tRechargeMoney.setBak2(shopId.toString());
        tRechargeMoney.setCreateBy(user.getUserId().toString());
        int i = tRechargeMoneyMapper.insertTRechargeMoney(tRechargeMoney);
        status = i == 0 ? "新增失败" : "新增成功";
        return Result.success(status);
    }

    /**
     * 查询充值赠送点数=金额
     *
     * @return
     */
    @GetMapping("/getRecharge")
    @ApiOperation(value = "查询充值赠送点数（金额）", httpMethod = "GET")
    public Result<TRechargeMoney> getRecharge() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        List<TRechargeMoney> monies = tRechargeMoneyMapper.selectTRechargeMoneyListByShopId(shopId);
        if (ObjectUtil.isEmpty(monies)) {
            return Result.success("暂无设置充值赠送数据");
        }
        return Result.success(monies);
    }

    /**
     * 每个店铺归属的会员列表
     *
     * @return
     */
    @GetMapping("/shopMember")
    @ApiOperation(value = "会员列表", httpMethod = "GET")
    public Result<TMember> shopMember() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        List<TMember> tMembers = itMemberService.selectTMemberByShopId(shopId);
        return Result.success(tMembers);
    }

    /**
     * 会员总数和今日新增
     *
     * @return
     */
    @GetMapping("/count")
    @ApiOperation(value = "会员总数和今日新增", httpMethod = "GET")
    public Result<MemberCountVo> count() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        MemberCountVo v = itMemberService.selectMemberCountAndToDayAdd(shopId);
        return Result.success(v);
    }

    /**
     * 兑换商品
     *
     * @return
     */
    @PostMapping("/exchange")
    @ApiOperation(value = "兑换商品", httpMethod = "POST")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "memberId", value = "会员id", dataType = "String", required = true),
            @ApiImplicitParam(name = "productId", value = "商品id", dataType = "String", required = true),
            @ApiImplicitParam(name = "number", value = "兑换数量", dataType = "String", required = true),
    })
    public Result exchange(@RequestBody ProductExchangeDto productExchangeDto) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        productExchangeDto.setShopId(shopId);
        productExchangeDto.setStaffId(user.getUserId());
        String s = commodityService.productExchange(productExchangeDto);
        return Result.success(s);
    }

    /**
     * 查询用户操作日志
     *
     * @return
     */
    @GetMapping("/operateLog/{memberId}")
    @ApiOperation(value = "查询用户操作日志", httpMethod = "GET")
    @RepeatSubmit
    public Result<TMemberLog> operateLog(@ApiParam("memberId ：会员id") @PathVariable("memberId") Long memberId) {
        List<TMemberLog> tMemberLog = tMemberLogService.selectTMemberLogByUserId(memberId);
        return Result.success(tMemberLog);
    }

    /**
     * 退款操作
     *
     * @return
     */
    @GetMapping("/refund/{memberId}/{money}/{remark}")
    @ApiOperation(value = "退款操作", httpMethod = "GET")
    @RepeatSubmit
    public Result<TMemberLog> refund(@ApiParam("会员id") @PathVariable("memberId") Long memberId,
                                     @ApiParam("金额") @PathVariable("money") Long money, @PathVariable String remark) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        TMember tMember = itMemberService.selectTMemberById(memberId);
        if (tMember.getStoredMoney().doubleValue() < money) {
            return Result.error("不允许退超过储值余额");
        }
        tMember.setBelongShop(shopId.toString());
        tMember.setId(memberId);
        tMember.setMoney(new BigDecimal(money));
        Integer i = itMemberService.updateTMemberRefund(tMember, user.getUserId(), shopId, remark);
        //

        String s = i == 1 ? "退款成功" : "操作失败,请重试";
        return Result.success(s);
    }


    /**
     * 退款操作
     *
     * @return
     */
    @GetMapping("/sendMoney/{memberId}/{money}/{remark}")
    @ApiOperation(value = "退款操作", httpMethod = "GET")
    @RepeatSubmit
    public Result<TMemberLog> sendMoney(@ApiParam("会员id") @PathVariable("memberId") Long memberId,
                                        @ApiParam("金额") @PathVariable("money") BigDecimal money, @PathVariable String remark) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());

        Integer i = itMemberService.updateTMemberSendMoney(memberId, money, user.getUserId(), shopId, remark);
        String s = i == 1 ? "赠送成功" : "操作失败,请重试";
        return Result.success(s);
    }



}
